/*
 * Copyright 2024 ywcai
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

`include "../core/defines.v"
`timescale 1ns/1ps

module myriscv_tb(
	);
	reg				    CLOCK_50;
	reg				    rst_n;
	reg[`IrqBus]	    irq;

    integer             fd_sig, fd_ram, fd_idx, err;
    reg[`RegDataBus]    loop;
    reg[`RegDataBus]	offset_data_end;

    wire[`RegDataBus]	sim_end_flag = i_riscv_top.i_ram._ram[(offset_data_end>>3)+2];
    wire[`RegDataBus]	begin_signature = i_riscv_top.i_ram._ram[offset_data_end>>3];
    wire[`RegDataBus]	end_signature = i_riscv_top.i_ram._ram[(offset_data_end>>3)+1];

	initial begin
		CLOCK_50 = 1'b0;
		forever #10 CLOCK_50 = ~CLOCK_50;
	end

	initial begin
		rst_n = `RESET_ENABLE;
		irq = 8'h0;
		#195 rst_n = `RESET_DISABLE;
//		#10000 $stop;

		$readmemh("myriscv.bin", i_riscv_top.i_rom._rom);

		//$readmemh("my.idx", offset_data_end);
		fd_idx = $fopen("my.idx", "r");
		$fscanf(fd_idx, "%h", offset_data_end);
		$fclose(fd_idx);

		fd_ram = $fopen("my.ds", "rb");
		err = $fread(i_riscv_top.i_ram._ram, fd_ram);
		$fclose(fd_ram);

		wait(sim_end_flag == `XLEN'h1);

		#20000;

		fd_sig = $fopen("DUT-myriscv.signature", "w");
		for (loop = begin_signature-`SDRAM_BASE; loop < end_signature-`SDRAM_BASE; loop = loop + 8) begin
			$fdisplay(fd_sig, "%h", i_riscv_top.i_ram._ram[loop>>3][31:0]);
			$fdisplay(fd_sig, "%h", i_riscv_top.i_ram._ram[loop>>3][63:32]);
		end
		$fclose(fd_sig);

		$display("===TEST END===");

        $finish;
	end

	riscv_top i_riscv_top(
		.clk(CLOCK_50),
		.rst_n(rst_n),
		.irq_i(irq)
	);

    initial begin
		#1000000;

		$display("===TIME OUT===");

        $finish;
    end

endmodule
